'''
Version: 2.0
Author: Yue Zhong
Date: 2024-12-27 21:32:24
Description: 
LastEditors: Yue Zhong
LastEditTime: 2025-01-09 13:43:30
'''
import inspect
import os
import re
import orjson
from typing import Dict, Callable

def read_config(config_path:str)->Dict:
    try:
        with open(config_path, 'rb') as f:
            config = orjson.loads(f.read())
        return config
    except:
        print("Error: config file is not a json file")
        return {}

def write_config(config_path:str, config:Dict)->None:
    try:
        with open(config_path, 'wb') as f:
            f.write(orjson.dumps(config))
        print("config file write successfully!")
    except:
        print("Error: config file is not a json file")

def isempty(x) -> bool:
    if x is None: return True
    elif isinstance(x, str):
        x = x.strip()
        return x in ['None','']
    elif isinstance(x, (list,tuple)): 
        return len(x) == 0
    elif isinstance(x, dict): 
        return len(x) == 0
    else:
        return False
    
def read_txt(path:str)->str:
    if os.path.exists(path):
        with open(path, 'r') as f:
            return f.read()
    else:
        return ""
    
def split_text_by_catagory(origin: str, catagory: str, suffix:bool=True, contain:bool=False) -> str:
        # 使用正则表达式提取 catagory 前面或后面的内容
        index = 0 if contain else 1
        if suffix:
            # 提取 catagory 后面的内容 , 需要包含本行
            pattern = re.escape(catagory) + r'(.*)'
        else:
            # 提取 catagory 前面的内容
            pattern = r'(.*)' + re.escape(catagory)
        match = re.search(pattern, origin, re.DOTALL)
        if match:
            return match.group(index).strip()
        else:
            # print(f"未找到 '{catagory}' {'后' if suffix else '前'}的内容, 将原样返回")
            return origin

def get_primitive_string(key:str, primitives_dict:Dict[str,Callable]):
    """
    获取 PRIMITIVES 字典中指定键的 lambda 函数的字符串表示。

    :param key: PRIMITIVES 字典中的键
    :param primitives_dict: PRIMITIVES 字典
    :return: 对应 lambda 函数的字符串表示
    """
    if key not in primitives_dict:
        raise KeyError(f"Key '{key}' not found in PRIMITIVES dictionary.")
    
    value = primitives_dict[key]
    
    if callable(value) and value.__name__ == "<lambda>":
        # 获取 lambda 函数的源代码
        source_code = inspect.getsource(value)
        # 去掉 lambda 关键字和冒号
        source_code = source_code.split('lambda', 1)[1].split(':', 1)[1].strip()
        # 保留 lambda 关键字
        # source_code = 'lambda' + source_code.split('lambda', 1)[1]
        # 去掉多余的空格和换行符
        source_code = source_code.strip().replace('\n', ' ')
        if source_code.endswith(','):
            source_code = source_code[:-1]
        return source_code
    else:
        # 如果不是 lambda 函数，直接返回其字符串表示
        return str(value)